package me.yuxiaoyao.example.lock.controller;

import me.yuxiaoyao.example.lock.response.ApiResponse;
import me.yuxiaoyao.lock.annotation.DistributedLock;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author kerryzhang on 2020/12/21
 */


@RestController
public class LockController {

    @DistributedLock(value = "#id", timeout = 1000L)
    @GetMapping("/param/{id}")
    public Object param(@PathVariable("id") Long id) throws InterruptedException {

        long startTime = System.currentTimeMillis();
        Thread.sleep(5 * 1000L);
        long endTime = System.currentTimeMillis();
        return ApiResponse.with(20000)
                .setData(id)
                .setPath("param")
                .setMessage("startTime:" + (startTime / 1000) + ". endTime:" + (endTime / 1000) + ".usageTime = " + (endTime - startTime))
                .build();
    }

    @DistributedLock(value = "#root.methodName")
    @GetMapping("/method")
    public Object methodLock() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread.sleep(5 * 1000L);
        long endTime = System.currentTimeMillis();
        return ApiResponse.with(20000)
                .setData("me.yuxiaoyao.example.lock.controller.TestController.method")
                .setPath("method")
                .setMessage("startTime:" + (startTime / 1000) + ". endTime:" + (endTime / 1000) + ".usageTime = " + (endTime - startTime))
                .build();
    }


    @DistributedLock(value = "'constKey'")
    @GetMapping("/constKey")
    public Object constKey() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread.sleep(5 * 1000L);
        long endTime = System.currentTimeMillis();
        return ApiResponse.with(20000)
                .setData("me.yuxiaoyao.example.lock.controller.TestController.constKey")
                .setPath("constKey")
                .setMessage("startTime:" + (startTime / 1000) + ". endTime:" + (endTime / 1000) + ".usageTime = " + (endTime - startTime))
                .build();
    }


    @DistributedLock(value = "#id + ':constKey'", timeout = 1000L)
    @GetMapping("/mixParam/{id}")
    public Object mixParam(@PathVariable("id") Long id) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread.sleep(5 * 1000L);
        long endTime = System.currentTimeMillis();
        return ApiResponse.with(20000)
                .setData("me.yuxiaoyao.example.lock.controller.TestController.mixParam")
                .setPath(id.toString())
                .setMessage("startTime:" + (startTime / 1000) + ". endTime:" + (endTime / 1000) + ".usageTime = " + (endTime - startTime))
                .build();
    }


}
